import mpx from "@mpxjs/core";
var timer = null;
var xtTimer=null;
var wb=null;
wb= {
    start() {
        var token = wx.getStorageSync('token')
        if (!token) {
                return 
        }
        const url = "wss://socket.weile999.com"
        mpx.connectSocket({
            url: url,
            header:{
              'content-type': 'application/json'
            }
        })
        mpx.onSocketOpen(function (res) {
            console.log("onopen")
            let param = JSON.stringify({ channel: 'auth', data: { token: token, content: "auth" } });
            mpx.sendSocketMessage({data:param})
            if(xtTimer){
                clearInterval(xtTimer)
                xtTimer=null
            }
            xtTimer=setInterval(()=>{
                let param = JSON.stringify({ channel: 'ping'});
                mpx.sendSocketMessage({data:param})
            },1000*30)
        })
        mpx.onSocketClose((res)=>{
            if (!token) {
                return 
            }
            console.log("isReconnecting.....")
            reconnect()
        })
        mpx.onSocketError((res)=>{
            if (!token) {
                return 
            }
            console.log("isReconnecting.....")
            reconnect()
        })

        // 重连
        function reconnect() {
            clearInterval(xtTimer)
            xtTimer=null
            clearTimeout(timer)
            timer = null;
            console.log(" start reconnect",wb)
            timer = setTimeout(()=>{     //没连接上会一直重连，设置延迟避免请求过多
             
                wb.start();
            }, 2000);
        }
       
    }
}
export default wb